package com.ndkj.rpcserver.common.utils;

import com.ndkj.rpcserver.common.dto.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 消费者网络调用RPC中间件（RPC-Server）
 */
public class HttpClient {

    /**RPC协议*/
    private static final String RPC_PROTOCOL = "http";

    /**请求方式*/
    private static final String RPC_METHOD = "POST";

    /**
     * 统一http发送post请求
     */
    public Object send(String host, Integer port, Invocation invocation) {
        try {
            URL url = new URL(RPC_PROTOCOL, host, port, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod(RPC_METHOD);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            // 阻塞获取
            InputStream inputStream = httpURLConnection.getInputStream();
            return IOUtils.toString(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
